package com.sike.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sike.entity.Emp;
import com.sike.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class StudentController {
    @Autowired
    ElasticsearchClient client;


    @GetMapping("/auto")  //路由到添加新书页面
    public String addStudent(){
        return "auto";
    }


    @GetMapping("/autocomplete")  //自动补全查询
    @ResponseBody
    public String autoComplete(String prefix) throws IOException {
        List<Student> list = new ArrayList<>();
        Suggester suggester = Suggester.of(s -> s.suggesters("university_suggest", p -> p.prefix(prefix).
                completion(c -> c.field("university").size(3).skipDuplicates(true))));
        //university_suggest是自定义的自动补全查询的名称，university是查询字段，必须是 completion类型。
        SearchRequest searchRequest = new SearchRequest.Builder().index("student").suggest(suggester).build();
        SearchResponse<Student> search = client.search(searchRequest, Student.class);
        int size=search.suggest().get("university_suggest").get(0).completion().options().size();//查询出来的结果条数
        for(int i=0;i<size;i++) {//处理查询结果，封装为泛型集合
            Student student=search.suggest().get("university_suggest").get(0).completion().options().get(i).source();
            list.add(student);
        }
        ObjectMapper objectMapper=new ObjectMapper();
        return objectMapper.writeValueAsString(list);
    }

    @GetMapping("/searchHightLight")  //转到视图
    public String searchHightLight(){
        return "searchHightLight";
    }

    @PostMapping("/searchHightLight") //根据关键字查询并高亮显示
    public ModelAndView search(String keyword) throws IOException {
        System.out.println("keyword:"+keyword);
        List<Student> list = new ArrayList<>();
        Query queryByName = Query.of(q -> q.match(m -> m.field("name").query(keyword)));
        String[] fields = {"name"}; //指定哪些字段要高亮
        Highlight highlightBuilder = Highlight.of(h -> { //设置高亮字段的效果，前后缀HTML标签
                    for (String field : fields) {
                        h.fields(
                                field
                                ,
                                h1 -> h1.preTags("<b><font color='red'>").postTags("</font></b>"));
                    }
                    return h;
                }
        );
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index("student")
                .query(queryByName)
                .highlight(highlightBuilder) //添加高亮效果
                .build();
        SearchResponse<Student> search = client.search(searchRequest, Student.class);
        for (Hit<Student> hit : search.hits().hits()) {
            Student student=hit.source();
            String name=hit.highlight().get("name").get(0);
            student.setName(name);//将原始字段name替换为高亮显示效果后的字段
            list.add(student);
        }
        ModelAndView mv=new ModelAndView();
        mv.addObject("students",list);
        mv.setViewName("students");
        return mv;
    }

//    @PostMapping("/search2") //多条件查询,选做
//    public ModelAndView search(Student student) throws IOException {
//
//        List<Student> list = new ArrayList<>();
//        Query queryByName = Query.of((q -> q.match(m -> m.field("name").query(student.getName()))));
//        Query queryByGender = Query.of((q -> q.match(m -> m.field("gender").query(student.getGender()))));
//        Query queryByAge = Query.of((q -> q.match(m -> m.field("age").query(student.getAge()))));
//        Query queryByCity = Query.of((q -> q.match(m -> m.field("city").query(student.getCity()))));
//
//        Query bool = Query.of(q -> q.bool(b -> b
//                .must(queryByName)
//                .must(queryByGender)
//                .must(queryByAge)
//                .must(queryByCity)));
//        SearchRequest searchRequest = new SearchRequest.Builder().index("student").query(bool).build();
//        SearchResponse<Student> search = client.search(searchRequest, Student.class);
//        for (Hit<Student> hit : search.hits().hits()) {
//            list.add(hit.source());
//        }
//        ModelAndView mv=new ModelAndView();
//        mv.addObject("students",list);
//        mv.setViewName("students");
//        return mv;
//    }

    //    @GetMapping("/findAllStudents") //查询所有学生信息
//    public ModelAndView findAllStudents() throws IOException {
//        List<Student> list = new ArrayList<>(); //备用，可以供其他类调用
//        Query queryAll = Query.of(q -> q.matchAll(m -> m));
//        SearchRequest searchRequest = new SearchRequest.Builder()
//                .index("student")
//                .query(queryAll)
//                .build();
//        SearchResponse<Student> search = client.search(searchRequest, Student.class);
//        for (Hit<Student> hit : search.hits().hits()) {
//            Student student=hit.source();
//            list.add(student);
//        }
//        ModelAndView mv=new ModelAndView();
//        mv.addObject("students",list);
//        mv.setViewName("students");
//        return mv;
//    }


}
